using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using PS.Practices.SiteBuilder.Features.Schema;
using PS.Practices.Util;

namespace PS.Practices.SiteBuilder.Features
{
    [CLSCompliant(false)]
    [Guid("dd0dfaa9-abcd-473a-9890-c2353c58c4a6")]
    public class PostCreationReceiver : SPFeatureReceiver
    {

        public virtual void OnActivated(SPFeatureReceiverProperties properties, SPWeb web)
        {
        }
        
        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            if (properties == null)
            {
                return;
            }

            SPWeb web = properties.Feature.Parent as SPWeb;
            string filePath = GetProvisioinerFilePath(web, properties.Feature.Properties);

            if (File.Exists(filePath) && web != null)
            {
                Interpreter interpreter = new Interpreter();
                interpreter.Process2(web, filePath);
            }

            OnActivated(properties, web);
        }

        internal static string GetProvisioinerFilePath(SPWeb web, SPFeaturePropertyCollection properties)
        {
            string siteDefDir = EnvironmentUtil.GetWSSSiteDefFolder();
            string filePath = String.Empty;
            if (web != null && !String.IsNullOrEmpty(siteDefDir))
            {
                string siteDefName = web.WebTemplate;
                string featureDir = Path.Combine(siteDefDir, siteDefName);

                SPFeatureProperty path = properties["ProvisionerPath"];
                string strPath = path != null ? path.Value : "xml\\provisioner.xml"; 
                filePath = Path.Combine(featureDir, strPath);
            }

            return filePath;
        }


        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }
    }
}
